package com.novel.controller.novel;

import com.github.pagehelper.PageInfo;
import com.novel.common.exception.CustomerException;
import com.novel.controller.other.BaseController;
import com.novel.pojo.novel.NovelComment;
import com.novel.pojo.system.User;
import com.novel.service.NovelCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("novel/comment")
public class NovelCommentController extends BaseController {

    @Autowired
    private NovelCommentService novelCommentService;

    /**
     * 分页查询评论内容
     */
    @GetMapping("query/page")
    @ResponseBody
    public PageInfo<NovelComment> queryCommentByPage(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                     @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                     @RequestParam(required = false) String userId,
                                                     String novelId, String chapterId) {
        return novelCommentService.queryCommentByPage(pageNum, pageSize, novelId, chapterId, userId);
    }

    /**
     * 添加评论
     */
    @PostMapping("add")
    public String insertCommentInfo(String novelId, String chapterId, String content, Integer sort) {

        User user = getUserInformation();

        if (user == null) {
            throw new CustomerException("用户未登录!");
        }

        NovelComment comment = NovelComment.builder()
                .chapterId(chapterId)
                .commentContent(content)
                .commentId(UUID.randomUUID().toString())
                .createdIp(getUserIpAddress())
                .createdTime(new Date())
                .novelId(novelId)
                .userId(user.getUserId())
                .userImg(user.getImgSrc())
                .userName(user.getUserName())
                .build();

        if (novelCommentService.insertCommentInfo(comment)) {
            return "redirect:/chapter/read/" + novelId + "/" + sort;
        }
        throw new CustomerException("评论失败!");
    }

    /**
     * 删除评论
     */
    @PostMapping("delete")
    public boolean deleteCommentInfoById(String commentId) {
        User user = getUserInformation();

        if (user == null) {
            throw new CustomerException("用户未登录!");
        }
        return novelCommentService.deleteCommentInfoByCommentId(commentId, user);
    }
}